import { ErrorPage } from '@/pages/error';
import { Outlet, useNavigate } from '@umijs/max';
import { observer } from 'mobx-react';
import { Component, ErrorInfo, PropsWithChildren } from 'react';
import styles from './default.less';
import { Menu } from './menu';
import { Dropdown, message } from 'antd';
import {history} from "@@/core/history";

enum EMenu {
  个人中心 = '1',
  退出登录 = '2',
}
class ErrorBoundary extends Component<PropsWithChildren> {
  state = {
    error: null,
    errorInfo: null,
  };

  constructor(props: any) {
    super(props);
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
    console.log(error);
    this.setState({
      error: error,
      errorInfo: errorInfo,
    });
  }

  render() {
    if (this.state.errorInfo) {
      return <ErrorPage />;
    }
    return this.props.children;
  }
}

const Layout = observer(() => {
  const navigate = useNavigate();
  const local = JSON.parse(localStorage.getItem('auth') || 'null');
  return (
    <div className={styles.container}>
      <div className={styles.headerContainer}>
        <img className={styles.logo} src={require('./assets/logo.png')} />

        <Dropdown
          arrow={{ pointAtCenter: true }}
          placement="bottom"
          trigger={['click']}
          overlayStyle={{ minWidth: '4em' }}
          menu={{
            onClick: (e) => {
              console.log(e);
              switch (e.key) {
                case EMenu.退出登录:
                  history.push('/login');
                  localStorage.clear();
                  message.success('退出成功');
                  break;
              }
            },
            items: [
              { key: EMenu.退出登录, label: '退出登录' },
            ],
          }}
        >
          <div className={styles.userBox}>
            <img className={styles.avatar} src={require('./assets/head.png')} />
            <span className={styles.username}>{local?.username}</span>
          </div>
        </Dropdown>
      </div>
      <div className={styles.contentContainer}>
        <Menu />
        <div className={styles.content}>
          <ErrorBoundary>
            <Outlet />
          </ErrorBoundary>
        </div>
      </div>
    </div>
  );
});
export default Layout;
